const domain = "https://www.99666666.xyz";
var httpRetryNum = 0;

function httpRequest(url, data, method, succ, fail, compt) {
  let retry = false;
  wx.request({
    url: domain + "/api" + url,
    data: data,
    method: method,
    header: {
      'content-type': 'application/json' // 默认值
    },
    timeout: 5000,
    success(res) {
      httpRetryNum = 0;
      if (res.data !== undefined) {
        if (res.data.code == 0) {
          if (succ) {
            succ(res.data);
          }
        } else {
          if (fail) {
            fail(res.data.msg);
          }
        }
      } else {
        console.log("S" + JSON.stringify(res));
        if (fail) {
          fail("request error");
        }
      }
    },
    fail(err) {
      let msg = JSON.stringify(err);
      console.log("F" + msg);
      if (msg != null && httpRetryNum < 2 && (msg.indexOf("time out") > 0 || msg.indexOf("timeout") > 0)) {
        httpRetryNum++;
        setTimeout(function () {
          httpRequest(url, data, method, succ, fail, compt);
        }, 2000, url, data, method, succ, fail, compt);
        retry = true;
        return;
      }
      httpRetryNum = 0;
      if (fail) {
        fail("request fail");
      }
    },
    complete() {
      if (!retry && compt) {
        compt();
      }
    }
  });
}

function httpGet(url, succ, fail, compt) {
  httpRequest(url, null, "GET", succ, fail, compt);
}

function httpPost(url, data, succ, fail, compt) {
  httpRequest(url, data, "POST", succ, fail, compt);
}

function isEmpty(value) {
  return (value == null || value == undefined || value.length == 0);
}

function isEmptyObj(obj) {
  return (obj == null || obj == undefined || Object.keys(obj).length === 0);
}

module.exports = {
  httpGet: httpGet,
  httpPost: httpPost,
  isEmpty: isEmpty,
  isEmptyObj: isEmptyObj,
};